﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using InternetShop.Code;

namespace InternetShop
{
    public partial class Site : System.Web.UI.MasterPage
    {
        protected Basket basket = new Basket();

        protected Basket CurrentBasket {
            get { 
                var b = (Basket)Session["Basket"];
                if (b == null)
                {
                    if (string.IsNullOrEmpty(Context.Profile.UserName))
                        b = new Basket();
                    else
                        b = Basket.LoadForUser(Context.Profile.UserName);
                    Session["Basket"] = b;
                }
                return b;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var regLnk = HeadLoginView.FindControl("RegisterHyperLink") as HyperLink;
            if(regLnk != null)
                regLnk.NavigateUrl = "Account/Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

            if (Context.User.IsInRole("Buyers"))
            {
                pBasket.Visible = true;
                rBasket.DataSource = CurrentBasket.Goods;
                rBasket.DataBind();
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            rBasket.DataSource = CurrentBasket.Goods;
            rBasket.DataBind();
            base.Render(writer);            
        }

        protected string GenerateBasketItem(object obj)
        {
            var item = obj as Product;
            return string.Format("{0} {1} {2}", item.Brand, item.Model, item.Price);
        }

        protected void rBasket_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Product pr = CurrentBasket.Goods.ElementAt(e.Item.ItemIndex);
            CurrentBasket.RemoveProduct(pr);
            Session["Basket"] = CurrentBasket;
            Response.Redirect(Request.RawUrl);
            rBasket.DataBind();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            CurrentBasket.Clear();
        }
    }
}